Implement Rand10() Using Rand7()

1. Question

Given the API rand7() that generates a uniform random integer in the range [1, 7], write a function rand10() that generates a uniform random integer in the range [1, 10]. You can only call the API rand7(), and you shouldn't call any other API. Please do not use a language's built-in random API.

Each test case will have one internal argument n, the number of times that your implemented function rand10() will be called while testing. Note that this is not an argument passed to rand10().

Follow up:

  • What is the expected value for the number of calls to rand7()function?
  • Could you minimize the number of calls to rand7()?

2. Examples

Example 1:

Input: n = 1
Output: [2]

Example 2:

Input: n = 2
Output: [2,8]

Example 3:

Input: n = 3
Output: [3,8,10]

3. Constraints

  • 1 <= n <= 105

4. References

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/implement-rand10-using-rand7 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

5. Solutions

玄学题

/**
 * The rand7() API is already defined in the parent class SolBase.
 * public int rand7();
 * @return a random integer in the range 1 to 7
 */
class Solution extends SolBase {
    public int getRes(){
        return (rand7()-1) * 7 + rand7() - 1;
    }

    public int rand10() {
        int res = getRes();
        while (res >= 40) {
            res=getRes();
        }
        return res % 10 + 1;
    }
}
/**
 * The rand7() API is already defined in the parent class SolBase.
 * public int rand7();
 * @return a random integer in the range 1 to 7
 */
class Solution extends SolBase {
    public int rand10() {
        int a = rand7();
        while (a == 4) {
            a = rand7();
        }

        int b = rand7();
        while (b >= 6) {
            b = rand7();
        }

        if (a < 4) {
            return b;
        } else {
            return b + 5;
        }
    }
}
Copyright © rootwhois.cn 2021-2022 all right reserved,powered by GitbookFile Modify: 2023-03-05 10:55:51

results matching ""

    No results matching ""